<template>
    <a-select v-bind="$attrs" v-on="$listeners" :placeholder="placeholder" v-model="currentValue">
        <a-icon v-if="fetching" style="color: #096dd9" slot="suffixIcon" type="loading" />
        <a-spin v-if="fetching" slot="notFoundContent" size="small" />
        <a-select-option selected v-for="i in departments" :key="i.id" :value="i.id">{{ i.name }}</a-select-option>
    </a-select>
</template>
<script>
import { getOrgManageList } from '@/api/system/system'
import { getDepartmentList } from '@/api/businessAffairs/revenueAndCost'
/*
 *  选择指定单位所有部门
 *
 * createBy:wnc
 * createTime:2021/5/8
 *
 * */
export default {
    name: 'SelectOrgDepartment',
    model: {
        event: 'change'
    },
    props: {
        // v-model绑定的数据
        value: {
            type: [Array, String, Object]
        },
        // placeholder
        placeholder: {
            type: String,
            default: function() {
                return '请选择'
            }
        },
        // 是否自动选中第一行
        autoSelected: {
            type: Boolean,
            default: () => true
        },
        isAutoSelectMe: {
            type: Boolean,
            default: () => false
        },
        orgId: {
            type: String,
            default: () => ''
        },
        form: {
            type: Object,
            default: () => ({})
        },
        // 需要联动的表单名
        keyValue: {
            type: String,
            default: () => 'unitId'
        },
        // orgId是否不能为空，为空不请求
        isOrgIdNotNull: {
            type: Boolean,
            default: () => false
        },
        // 是否是搜索框，如果是的话，orgId改变会清空当前值
        isSearch: {
            type: Boolean,
            default: () => false
        }
    },
    data() {
        return {
            fetching: false,
            departments: []
        }
    },
    watch: {
        orgId(v) {
            if (v) {
                this.getCompanyList()
            }
        },
        attr(v) {
            if (this.isSearch){
                this.currentValue = undefined
            }
            if (!v) {
                if (this.isOrgIdNotNull) return this.departments = []
            }
            if (v) {
                this.getCompanyList()
            }
        }
    },
    created() {
        this.orgId && this.getCompanyList()
    },
    methods: {
        async getCompanyList() {
            this.fetching = true
            let data = {
                id: this.attr || this.orgId,
                type: '2'
            }
            let res3 = await getDepartmentList(data)
            this.fetching = false
            this.departments = res3.data || []
            if (this.isAutoSelectMe) {
                let res2 = this.departments.find((v) => v.id === this.$currentPost().deptId)
                if (res2) {
                    this.currentValue = res2.id
                }
            }
            if (this.autoSelected && !this.currentValue) {
                this.currentValue = this.departments[0].id
            }
        },
        filterOption(input, option) {
            return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
    },
    computed: {
        // 需要联动的表单值
        attr() {
          let attrValue
          const keys = this.keyValue.split('.')
          const findValueFromKeys = (data, key) => {
            if(data instanceof Object && keys.some(k => k === key)){
              return findValueFromKeys(data[key], keys[keys.findIndex(k => k === key) + 1])
            }
            return data
          }
          if(keys && !!keys.length){
            attrValue = findValueFromKeys(this.form, keys[0])
          }
          return attrValue || this.orgId
        },
        // 转换绑定的选中数据，与v-model同步
        currentValue: {
            get: function() {
                if (this.departments.length > 0) {
                    this.$emit(
                        'update:option',
                        this.departments?.find((item) => item.id === this.value)
                    )
                    this.$emit(
                        'getOption',
                        this.departments.find((item) => item.id === this.value)
                    )
                }
                return this.value
            },
            set: function(value) {
                // this.$emit('input', value)
                this.$emit('change', value)
                let res2 = this.departments.find((v) => v.id === value)
                if (res2) {
                    this.$emit('onSelectChange', res2)
                }
            }
        }
    }
}
</script>
